package com.yxx.community.interceptor;

import com.yxx.community.mapper.UserMapper;
import com.yxx.community.model.User;
import com.yxx.community.model.UserExample;
import com.yxx.community.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Author: YuXinXin
 * @Description:
 * @Date:Created in 21:27 2020/1/28
 **/
@Component
public class SessionInterceptor implements HandlerInterceptor {

  @Autowired
  private UserMapper userMapper;
  @Autowired
  private NotificationService notificationService;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
    User user;
    Cookie[] cookies = request.getCookies();
    if (cookies!=null)
    {
      for (Cookie cookie : cookies) {
        if(cookie.getName().equals("token")){
          String token = cookie.getValue();
          UserExample userExample = new UserExample();
          userExample.createCriteria().andTokenEqualTo(token);
          List<User> users = userMapper.selectByExample(userExample);
          if (users.size()!=0){
            request.getSession().setAttribute("user",users.get(0));
            int ureadCount=notificationService.ureadCount(users.get(0).getId());
            request.getSession().setAttribute("ureadCount",ureadCount);
          }
          break;
        }
      }
    }
    return true;
  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

  }

  @Override
  public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

  }
}
